//
//  ScanDevice.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/13.
//

import SwiftUI
import UTEBluetoothRYApi
import ToastUI

struct ScanDevice: View {
    
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel: ScanDeviceVM
    
    init(appState: AppState) {
        _viewModel = StateObject(wrappedValue: ScanDeviceVM(appState: appState))
    }
    
    var rotateAnimation: Animation {
        Animation.linear(duration: 3)
            .repeatForever(autoreverses: false)
    }
    
    var body: some View {
        ZStack(alignment: .top) {
            Color(hex: "#0A0A0A")
                .ignoresSafeArea()
            VStack(spacing: 0) {
                ZStack {
                    HStack {
                        Button(action: {
                            appState.navigateBack()
                        }) {
                            Image("back")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 16, height: 16)
                                .padding(.horizontal, 12)
                        }
                        Spacer()
                    }
                    .frame(height: 44)
                    Text("添加设备")
                        .font(.system(size: 18, weight: .medium))
                        .foregroundColor(.white)
                }
                
                ZStack(alignment: .top) {
                    Button(action: {
                        if viewModel.isScanning == false {
                            viewModel.scanDevice()
                        }
                    }) {
                        Text("重新扫描")
                            .padding(.horizontal, 20)
                            .frame(maxWidth:.infinity, alignment: .leading)
                            .frame(height: 56)
                            .font(.system(size: 16, weight: .regular))
                            .foregroundColor(.white)
                            .background(Color(hex: "#1E1E1E"))
                            .cornerRadius(16)
                    }
                    .padding(.horizontal, 12)
                    .padding(.top, 12)
                    .opacity(viewModel.isScanning == false && viewModel.devices.isEmpty ? 1 : 0)
                    .disabled(viewModel.isScanning == false && viewModel.devices.isEmpty ? false : true)
                    
                    VStack(spacing: 0) {
                        ZStack(alignment: .topLeading) {
                            Image("radar_bg")
                                .resizable()
                                .frame(width: 280, height: 280)
                                .aspectRatio(contentMode: .fit)
                            Image("radar_scanning")
                                .frame(width: 96, height: 139)
                                .padding(.leading, 44)
                                .rotationEffect(.degrees(viewModel.isScanning ? 360 : 0), anchor: .bottomTrailing)
                                .animation(
                                    rotateAnimation,
                                    value: viewModel.isScanning
                                )
                                .opacity(viewModel.isScanning ? 1 : 0)
                                .disabled(!viewModel.isScanning)
                                .id(viewModel.animationFlag)
                                
                        }
                        .padding(.top, 30)
                        .opacity(viewModel.isScanning || viewModel.devices.isEmpty == false ? 1 : 0)
                        .disabled(viewModel.isScanning == false && viewModel.devices.isEmpty ? true : false)
                        
                        Text("正在扫描")
                            .padding(.top, 24)
                            .frame(maxWidth:.infinity, alignment:  .center)
                            .font(.system(size: 20, weight: .medium))
                            .foregroundColor(Color(hex: "#B2B2B2"))
                            .opacity(viewModel.isScanning ? 1 : 0)
                            .disabled(viewModel.isScanning ? false : true)
                        
                        ScrollView {
                            VStack(spacing: 15) {
                                ForEach(0..<$viewModel.devices.count, id: \.self) { index in
                                    let device = viewModel.devices[index]
                                    ZStack {
                                        Color(hex: "#1E1E1E")
                                            .cornerRadius(16, corners: .allCorners)
                                            .frame(height: 102)
                                        HStack(spacing: 12) {
                                            Image("")
                                                .frame(width: 70, height: 70)
                                                .background()
                                            VStack(alignment: .leading, spacing: 8) {
                                                Text(device.name)
                                                    .font(.system(size: 16, weight: .medium))
                                                    .foregroundColor(.white)
                                                Text(device.advertisementAddress.formattedMACAddress() ?? "")
                                                    .font(.system(size: 14, weight: .regular))
                                                    .foregroundColor(Color(hex: "#C6C6C6"))
                                                Spacer()
                                            }
                                            .padding(.vertical, 4)
                                            
                                            Spacer()
                                            Button(action: {
                                                viewModel.connectDevice(device: device)
                                            }) {
                                                Text("连接")
                                                    .font(.system(size: 16, weight: .medium))
                                                    .foregroundColor(Color(hex: "#242424"))
                                                    .frame(width: 80, height: 40)
                                                    .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")])
                                                    .cornerRadius(20)
                                            }
                                        }
                                        .padding(.all, 16)
                                    }
                                }
                            }
                            
                        }
                        .padding(.horizontal, 12)
                        .padding(.top, 16)
                    }
                }
                
                Spacer()
                Button(action: {
                    
                }) {
                    Text("扫码添加")
                        .frame(maxWidth:.infinity, alignment: .center)
                        .frame(height: 44)
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(Color(hex: "#242424"))
                        .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")])
                        .cornerRadius(20)
                }
                .padding(.horizontal, 12)
            }
            
            if appState.isLoading {
                Color(.white).opacity(0.1)
                    .ignoresSafeArea()
                VStack() {
                    Spacer()
                    ZStack {
                        Color.white
                            .frame(width: 120, height: 120)
                            .cornerRadius(16)
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: .black))
                            .scaleEffect(2)
                    }
                    Spacer()
                }
            }
            
        }
        .navigationBarHidden(true)
        .onAppear {
            viewModel.scanDevice()
        }
        .onDisappear {
            UTEBluetoothMgr.sharedInstance().delegate = nil
            viewModel.stopScanDevice()
        }
        .onChange(of: viewModel.pairedDevice) { newValue in
            if newValue.isConnected {
                let lastDevice = DeviceInfo(from: viewModel.pairedDevice)
                appState.currentDevice = lastDevice
                appState.navigateReplaceCurrent(to: .deviceSetting(id: viewModel.pairedDevice))
            }
        }
        .onChange(of: appState.showError) { newValue in
            if newValue == true {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    appState.showError = false
                    appState.errorMessage = nil
                }
            }
        }
        .toast(isPresented: $appState.showError) {
            ShowMessageView(message: appState.errorMessage)
            /*   ToastView(appState.errorMessage ?? "")
                .foregroundColor(.white)
                .background(Color.black.opacity(0.8))
                .cornerRadius(8)
                .edgesIgnoringSafeArea(.all) */
        }
        .alert(isPresented: $appState.showAlert, content: {
            Alert(
                title: Text("提示"),
                message: Text("请到系统蓝牙设置中，断开设备连接后重试"),
                dismissButton: .default(Text("确认"), action: {
                    appState.showAlert = false
                })
            )
        })
    }
}

//#Preview {
//    ScanDevice()
//}
